#!/bin/sh

#更改工作目录
pwd
cd `dirname $0`
pwd

var_g_script_file=$(basename $BASH_SOURCE)

. ./conf.sh

#linux命令
PIDOF=/sbin/pidof

#检查环境
check_env()
{
    local username=`whoami`
    if [ "$username" != "root" ]; then
        echo "please use the root user to run"
        exit
    fi
    
    return 1;
}

VAR_FLAG_DEBUG=R

#常用定义(根据环境修改下面参数)
var_g_app_path=$VAR_G_APP_PATH
var_g_app_name="apm"
var_g_dssl_name="apmdssl"
var_g_app_param=" -n -i $VAR_DEV --ring_size 256 "
var_g_dssl_param=" -i $VAR_DEV "

#运行环境检查
check_env;

#检查脚本是否已在运行
mkdir -p /var/run/apm
pidfile=/var/run/apm/run_apm_c.pid
if [ -s $pidfile ]; then
    ls /proc/$(cat ${pidfile}) >/dev/null 2>&1
    if [ $? -eq 0 ]; then
        cat /proc/$(cat ${pidfile})/cmdline | grep -q "$var_g_script_file"
        if [ $? -eq 0 ]; then
            echo "$0 is running"
            exit 1
        else
            echo $$ > $pidfile
        fi
    else
        echo $$ > $pidfile
    fi
else
    echo $$ > $pidfile
fi

# 获取参数 $1:D表示debug版本
if [ $# -ge 1 ]; then
    if [ "$1" == "D" -o "$1" == "-D" -o "$1" == "d" -o "$1" == "-d" ]; then
        VAR_FLAG_DEBUG=D
    fi
fi

#调式版本
if [ "$VAR_FLAG_DEBUG" == "D"  ]; then
    var_g_app_path="../bin"
    var_g_app_param=" -n -i $VAR_DEV "
fi

# 检查apm是否已经运行
var_app_cnt=`${PIDOF} ${var_g_app_name} | wc -l`
if [ ${var_app_cnt} -gt 0 ]; then
    echo "${var_g_app_name} is running"
else
    #配置lua运行环境变量
    export LUA_PATH="../lib/?.lua;../lualib/framework/?.lua;../lualib/lib/?.lua;/usr/share/lua/5.1/?.lua;${LUA_PATH}" 
    export LUA_CPATH="../lib/?.so;../lualib/lib/?.so;/usr/lib/lua/5.1/?.so;${LUA_CPATH}"
    # 运行程序apm
    cd ${var_g_app_path}
    nohup ./${var_g_app_name} ${var_g_app_param} > /dev/null 2>&1 &
    echo "run ./${var_g_app_name} ${var_g_app_param}"
fi

# 检查dssl是否已经运行
var_app_cnt=`${PIDOF} ${var_g_dssl_name} | wc -l`
if [ ${var_app_cnt} -gt 0 ]; then
    echo "${var_g_dssl_name} is running"
else
    # 运行程序apmdssl
    cd ${var_g_app_path}
    nohup ./${var_g_dssl_name} ${var_g_dssl_param} > /dev/null 2>&1 &
    
    echo "run ./${var_g_dssl_name} ${var_g_dssl_param}"
fi

